package com.hongawen.poi.service;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.util.CharsetUtil;
import com.hongawen.poi.pojo.Student;
import com.hongawen.poi.pojo.Tree;
import com.hongawen.poi.util.HttpServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author hongawen
 * @version 1.0.0
 * @date 2022年03月30日 18:41
 */
@Slf4j
@Component
public class TreeService {

    private static List<Tree> treeList = new ArrayList<>();

    static {
        Tree tree;
        List<Tree> treeList1 = new ArrayList<>();
        List<Tree> treeList2 = new ArrayList<>();
        for (int i = 1; i < 5; i++) {
            tree = new Tree();
            tree.setName("孙子集合" + i + "号");
            tree.setId(UUID.randomUUID().toString());
            treeList1.add(tree);
        }


        for (int i = 1; i < 5; i++) {
            tree = new Tree();
            tree.setName("儿子集合" + i + "号");
            tree.setId(UUID.randomUUID().toString());
            tree.setChildren(treeList1);
            treeList2.add(tree);
        }

        for (int i = 1; i < 5; i++) {
            tree = new Tree();
            tree.setName("父级集合" + i + "号");
            tree.setId(UUID.randomUUID().toString());
            tree.setChildren(treeList2);
            treeList.add(tree);
        }


    }


    public void exportTree() {
        try {
            HttpServletResponse response = HttpServletUtil.getResponse();
            String fileName = URLEncoder.encode("hello.xls", CharsetUtil.UTF_8);
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            response.setContentType("application/octet-stream;charset=UTF-8");
            ServletOutputStream outputStream = response.getOutputStream();
            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), Tree.class, treeList);
            workbook.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            log.error(">>> 导出数据异常：{}", e.getMessage());
        }
    }


}
